package com.dong.policy.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zhaodongchao
 * @date 2020/11/17 16:20
 */
@Configuration
@EnableAsync
public class MyAsyncConfigurer implements AsyncConfigurer {
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return myAsyncUncaughtExceptionHandler();
    }

    @Override
    public Executor getAsyncExecutor() {
        return apiTaskAsyncPool();
    }

    @Bean
    public AsyncUncaughtExceptionHandler myAsyncUncaughtExceptionHandler(){
        return new MyAsyncUncaughtExceptionHandler();
    }
    @Bean("TaskAsyncPool")
    public ThreadPoolTaskExecutor apiTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(1000);
        executor.setThreadNamePrefix("TaskAsyncPool");
        // 如果QueueCapacity数不足,采用本地执行方式
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();
        return executor;
    }
}
